package com.wz.jiangsu.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * @author syl
 * @description 配置线程池
 * @since 2021/4/23
 */
@Configuration
@Slf4j
//开启异步
@EnableAsync
public class ThreadPoolConfig {


    @Bean("threadPoolTaskExecutor")
    public Executor getThreadPoolTaskExecutor(){
        log.info("配置线程池----------------");
        ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(10);
        //最大线程数
        executor.setMaxPoolSize(50);
        //队列容量
        executor.setQueueCapacity(10);
        //线程名前缀
        executor.setThreadNamePrefix("taskExecutor-");
        //线程池中corePoolSize线程空闲时间达到keepAliveTime是否关闭
        executor.setAllowCoreThreadTimeOut(false);
        //线程超时时间
        executor.setKeepAliveSeconds(100);
        //rejection-policy：当pool已经达到max size的时候，如何处理新任务
        //CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        //对拒绝task的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //设置线程池关闭的时候是否等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁
        // 以确保应用最后能够被关闭，而不是阻塞住。
        executor.setAwaitTerminationSeconds(60);
        //加载
        executor.initialize();
        return executor;
    }
}
